<template>
  <!-- https://blog.csdn.net/qq_41619796/article/details/107952904 -->
  <!-- https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia -->
  <div>
    <div class="video_box">
      <video id="video1" muted playsinline autoplay></video>
      <div class="motai"></div>
    </div>
    <!-- <button @click="startCamera()">开始</button> -->
    <button @click="changeFacingMode()">change</button>
    <button @click="startRecording()">开始录制（先点）</button>
    <button @click="stopAndblobDownload()">下载录像（再点）</button>
    <button @click="catchPic()">抓图</button>
    <video v-if="video2Src" id="video2" :src="video2Src" controls loop autoplay></video>
    <img :src="picSrc" alt="" id="img" />
  </div>
</template>
<script>
import Adapter from "adapterjs";
import RecordRTC from "recordrtc";
export default {
  data() {
    return {
      recorder: null,
      facingMode: "user",
      currentStream: null,
      video1Dom: null,
      video2Src: null,
      picSrc: null,
    };
  },
  mounted() {
    this.startCamera();
  },
  methods: {
    //开启摄像头
    async startCamera() {
      this.video2Src = "";
      await this.$nextTick();
      //webRTCReady为了执行任何与WebRTC相关的代码，您必须等待函数触发参数，因为当WebRTC接口准备好供浏览器使用时，该参数被触发
      Adapter.webRTCReady((isUsingPlugin) => {
        console.log("开启摄像头");
        this.video1Dom = document.getElementById("video1");
        if (this.currentStream) this.stopMediaTracks(this.currentStream);
        const constraints = {
          video: {
            facingMode: this.facingMode,
          },
          audio: true,
        };
        const successFn = (stream) => {
          console.log("用户授权了");
          this.currentStream = stream;
          console.log(Adapter);
          //attachMediaStream这是为了与Google的原始版本兼容而接管的。将对象馈送到视频和音频标签中。调用将从元素中分离任何现有流。流仍将运行，并可附加到任何呈现元素。
          Adapter.attachMediaStream(this.video1Dom, stream);
          this.video1Dom.onloadedmetadata = (e) => {
            this.video1Dom.play();
          };
        };
        const errorFn = (err) => {
          console.log(err);
          console.log("用户取消了");
        };

        Adapter.getUserMedia(constraints, successFn, errorFn);
      });
    },

    //停止媒体
    stopMediaTracks(stream) {
      console.log("停止媒体");
      stream.getTracks().forEach((track) => {
        track.stop();
      });
    },

    //变换前后置
    changeFacingMode() {
      console.log("变换前后置");

      this.facingMode = this.facingMode === "user" ? "environment" : "user";

      this.startCamera();
    },

    //开始录像
    startRecording() {
      console.log("开始录像");
      this.recorder = RecordRTC(this.currentStream, {
        type: "video",
      });
      this.recorder.startRecording();
      // this.recorder.camera = this.currentStream;
    },
    //结束录像
    async stopAndblobDownload() {
      console.log("停止录像");
      this.recorder.stopRecording(() => {
        this.video2Src = URL.createObjectURL(this.recorder.getBlob());
        console.log(this.video2Src);
        // this.recorder.camera.stop();
        this.recorder.destroy();
        this.recorder = null;
      });
    },

    //抓图
    catchPic() {
      var canvas = document.createElement("canvas");
      canvas.width = this.video1Dom.videoWidth;
      canvas.height = this.video1Dom.videoHeight;
      canvas
        .getContext("2d")
        .drawImage(this.video1Dom, 0, 0, canvas.width, canvas.height);

      const src = canvas.toDataURL("image/png");
      console.log(src);
      this.picSrc = src;
    },
  },
};
</script>
<style>
.video_box {
  width: 600px;
  height: 428px;
  border: 1px solid red;
  position: relative;
}
#video1 {
  width: 100%;
  height: 100%;
  object-fit: scale-down;
}
.motai {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1;
  background: url("../assets/face.png") no-repeat 0 0 /100% 100%;
  width: 100%;
  height: 100%;
}
#video2,
#img {
  width: 500px;
  height: 500px;
  /* fit: cover; */
  object-fit: cover;
}
</style>
